package Script;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;

import Error.StandardError;
import Language.Language;

import interfaces.ErrorReport;
import interfaces.Pointer;
import interfaces.ErrorReport.ErrorType;

public class JPointerWriter {

	public static ArrayList<ErrorReport> write(File file,
										HashMap<Integer, Pointer> pointers) {
		ArrayList<ErrorReport> err = new ArrayList<ErrorReport>();
		ArrayList<Pointer> pList = new ArrayList<Pointer>(pointers.values());
		RandomAccessFile write = null;
		Offset off;
		
		/* Abort if pointer collection is empty. */
		if (pointers.size() < 1) {
			return err;
		}
		
		try {
			write = new RandomAccessFile(file, "rw");
			
			for (Pointer p : pList) {
				
				/* Get file offset. */
				off = p.getFileOffset();
				
				/* Jump to that position in the file. */
				write.seek(off.getValue());
				
				/* Print the pointers byte-value. */
				write.write(p.printValue());
			}
			
		} catch (FileNotFoundException e) {
			err.add(new StandardError(Language.noGamefile, ErrorType.ERROR));
			return err;
			
		} catch (IOException e) {
			err.add(new StandardError(Language.writeError, ErrorType.ERROR));
			return err;
			
		} finally {
			
			/* End by closing the file. */
			try {
				if (write != null) {
					write.close();
				}
			} catch (IOException e) {
				
			}
		}
		
		return err;
	}

}
